<template>

    <div class="card" style="margin-bottom: 10px">
      <el-input placeholder="请输入药品名称进行查询" style="width: 200px" v-model="data.productName"></el-input>
      <el-button type="primary"  style="margin-left: 10px" @click="loadData">查询</el-button>
      <el-button type="warning"  style="margin-left: 10px" @click="reset">重置</el-button>
    </div>
  <div class="card" style="margin-bottom: 5px">
    <div class="table">
      <div style="margin: 0 0 20px 0">
        <el-button type="primary" plain @click="editOrNot('','editTable')" v-if="!data.editTableOrNot">批量录入盘点数据</el-button>
        <el-button type="danger"  style="margin-left: 10px" @click="editOrNot('','cancelEditTable')" v-if="data.editTableOrNot">取消</el-button>
        <el-button type="primary"  style="margin-left: 10px" @click="handelEditBatch" v-if="data.editTableOrNot">确定批量盘点</el-button>
      </div>

      <el-table :data="data.tableData" stripe max-height="450px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" fixed="left"></el-table-column>
        <el-table-column prop="productName" label="药品名称" fixed="left"></el-table-column>
        <el-table-column label="药品图片" fixed="left" width="120px">
          <template #default="scope">
            <el-image
                :src="scope.row.imageUrl"
                :preview-src-list="[scope.row.imageUrl]"
                preview-teleported
                style="width: 40px; height: 40px; border-radius: 50%"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="stockQuantity" label="盘点的库存数" width="180px">
          <template #default="scope">
            <el-input-number v-model="scope.row.stockQuantity" :min="1" placeholder="请输入盘点的库存数量"  v-if="data.editRow === scope.row.sellerProductId || data.editTableOrNot" />
          </template>
        </el-table-column>
        <el-table-column prop="currentStock" label="当前系统库存数" width="120px" ></el-table-column>
        <el-table-column prop="unit" label="单位"></el-table-column>
        <el-table-column prop="stockTakingUserName" label="盘点人姓名" width="120px"></el-table-column>
        <el-table-column prop="stockTakingDate" label="盘点时间" width="170"></el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template v-slot="scope">
            <el-button size="mini" type="primary" plain @click="editOrNot(scope.row,'editRow')" v-if="data.editRow !==scope.row.sellerProductId">录入盘点数据</el-button>
            <el-button size="mini" type="danger" plain @click="editOrNot(scope.row,'cancelEditRow')" v-if="data.editRow ===scope.row.sellerProductId" >取消</el-button>
            <el-button size="mini" type="primary"  @click="handleEdit(scope.row,)" v-if="data.editRow ===scope.row.sellerProductId" >确定</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
            style="margin-top: 5px"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="data.pageNum"
            :page-sizes="[3, 5, 10, 15, 20]"
            :page-size="data.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, onBeforeMount, onBeforeUnmount, onUnmounted, getCurrentInstance, toRefs, watch, nextTick } from 'vue'
import {loadSellerProductApi, saveSellerProductApi, updateBatch} from "@/utils/API/shop/SellerProduct";
import {ElMessage, ElMessageBox} from "element-plus";
const data = reactive({
  tabelData:[],
  pageNum:1,
  pageSize:10,
  total:0,
  editRow:0,
  editTableOrNot:false,
  ids:[],
  productName:'',
  stockTakingUserName:'',
  user:JSON.parse(localStorage.getItem('system-user')||'{}')

})
//加载库存数据
const loadData =()=>{
  let params={
    productName:data.productName,
    pageNum:data.pageNum,
    pageSize:data.pageSize
  }
  loadSellerProductApi(params).then(res=>{
    if(res.code==='200'){
      console.log(res)
      data.tableData=res.data?.list
      data.total=res.data?.total
    }
  })
}

const editOrNot =(row,op)=>{
  switch (op){
    case 'editRow':
      data.editRow = row.sellerProductId
      break;
    case 'cancelEditRow':
      loadData()
      data.editRow = 0
      break;
    case 'editTable':
      data.editTableOrNot = true
      break;
      case 'cancelEditTable':
        loadData()
        data.editTableOrNot = false
        break;
  }

}
//库存盘点
const handleEdit=(row)=> {
  row.stockTakingUserName = data.user.name
  row.stockTakingDate = formateDate()
  if (row.stockQuantity === 0) {
    ElMessage.error('盘点的库存数量不能为0')
    return
  }
  ElMessageBox.confirm('确定要录入药品'+row.productName+'的盘点数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    saveSellerProductApi(row).then(res => {
      if (res.code === '200') {
        ElMessage.success('成功录入'+row.productName+'的盘点数据')
        loadData()
        data.editRow = 0
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
  const handelEditBatch = ()=>{
    for(let i=0;i<data.tableData.length;i++){
      if(data.tableData[i].stockQuantity===0){
        ElMessage.error('盘点的库存数量不能为0')
        return
      }
      data.tableData[i].stockTakingUserName = data.user.name
      data.tableData[i].stockTakingDate = formateDate()
    }
    ElMessageBox.confirm('确定要录入所有药品的盘点数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      updateBatch(data.tableData).then(res=>{
        if(res.code==='200'){
          ElMessage.success('盘点数据批量录入成功')
          loadData()
          data.editTableOrNot = false
        }else{
          ElMessage.error(res.msg)
        }
      })
    })
  }


//处理选中的数据
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.sellerProductId)
}

//时间重塑，用于时间格式化，更新数据时记录
const formateDate =()=>{
  const date = new Date();  // 获取当前时间
  const year = date.getFullYear();  // 获取年份
  const month = String(date.getMonth() + 1).padStart(2, '0');  // 获取月份，注意需要 +1
  const day = String(date.getDate()).padStart(2, '0');  // 获取日期
  const hours = String(date.getHours()).padStart(2, '0');  // 获取小时
  const minutes = String(date.getMinutes()).padStart(2, '0');  // 获取分钟
  const seconds = String(date.getSeconds()).padStart(2, '0');  // 获取秒数

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const reset =()=>{
  data.productName = ''
  loadData()
}

// 处理页码变化
const handleCurrentChange = (pageNum) => {
  data.pageNum = pageNum
  load()
}
const handleSizeChange=(pageSize)=> {
  data.pageSize = pageSize
  load()
}
// 处理选中的行
onMounted(()=>{
  loadData()
})
</script>

<style scoped>
@import '@/assets/css/tabelContent.css';
</style>